<template>
  <div class="creator-center-container">
    <n-card class="creator-card">
      <template #header>
        <div class="card-header">
          <h1>创作者中心</h1>
          <div class="header-actions">
            <n-button @click="refreshData" :loading="loading">
              <template #icon><n-icon>
                  <RefreshOutline />
                </n-icon></template>
              刷新数据
            </n-button>
              </div>
            </div>
                  </template>

      <n-tabs type="line" animated>
        <!-- 作品管理标签页 -->
        <n-tab-pane name="works" tab="作品管理">
          <div class="tab-content">
            <div class="section-header">
              <h3>我的作品</h3>
              <n-space>
                <n-input-group>
                  <n-input v-model:value="worksSearch" placeholder="搜索作品" />
                  <n-button type="primary">
                    <template #icon><n-icon>
                        <SearchOutline />
                      </n-icon></template>
              </n-button>
                </n-input-group>
                <n-select v-model:value="worksFilter" :options="worksFilterOptions" style="width: 120px" />
              </n-space>
            </div>
            
            <n-data-table :columns="worksColumns" :data="filteredWorks" :loading="loading" :pagination="pagination"
              :bordered="false" striped />
          </div>
        </n-tab-pane>
        
        <!-- 素材管理标签页 -->
        <n-tab-pane name="assets" tab="素材管理">
          <div class="tab-content">
            <div class="section-header">
              <h3>我的素材</h3>
              <n-space>
                <n-button type="primary" @click="showUploadModal = true">
                  <template #icon><n-icon>
                      <CloudUploadOutline />
                    </n-icon></template>
                  上传素材
              </n-button>
                <n-input-group>
                  <n-input v-model:value="assetsSearch" placeholder="搜索素材" />
                  <n-button type="primary">
                    <template #icon><n-icon>
                        <SearchOutline />
                      </n-icon></template>
                  </n-button>
                </n-input-group>
                <n-select v-model:value="assetsFilter" :options="assetsFilterOptions" style="width: 120px" />
              </n-space>
            </div>
            
            <n-grid :cols="4" :x-gap="12" :y-gap="12" responsive="screen">
              <n-grid-item v-for="asset in filteredAssets" :key="asset.id">
                <n-card :title="asset.name" class="asset-card" hoverable>
                  <template #cover>
                    <img :src="asset.thumbnail" class="asset-thumbnail" />
                  </template>
                  <div class="asset-info">
                    <div class="asset-meta">
                      <n-tag :type="getAssetStatusType(asset.status)">{{ getAssetStatusText(asset.status) }}</n-tag>
                      <span>{{ formatDate(asset.createdAt) }}</span>
                    </div>
                    <div class="asset-stats">
                      <span><n-icon>
                          <DownloadOutline />
                        </n-icon> {{ asset.downloadCount }}</span>
                      <span><n-icon>
                          <StarOutline />
                        </n-icon> {{ asset.rating }}</span>
                    </div>
                  </div>
                  <template #footer>
                    <div class="asset-actions">
                      <n-button-group size="small">
                        <n-button @click="editAsset(asset.id)">编辑</n-button>
                        <n-button @click="viewAssetStats(asset.id)">数据</n-button>
                        <n-button @click="deleteAsset(asset.id)" type="error">删除</n-button>
                      </n-button-group>
                    </div>
                  </template>
                </n-card>
              </n-grid-item>
            </n-grid>

            <div class="pagination-container">
              <n-pagination v-model:page="assetsPage" :page-count="assetsTotalPages" />
            </div>
          </div>
        </n-tab-pane>
        
        <!-- 收益统计标签页 -->
        <n-tab-pane name="earnings" tab="收益统计">
          <div class="tab-content">
            <div class="earnings-summary">
              <n-grid :cols="3" :x-gap="12">
                <n-grid-item>
                  <n-statistic label="总收益">
                    <n-number-animation :from="0" :to="totalEarnings" :duration="1000" />
                    <template #suffix>元</template>
                  </n-statistic>
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="本月收益">
                    <n-number-animation :from="0" :to="monthlyEarnings" :duration="1000" />
                    <template #suffix>元</template>
                  </n-statistic>
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="可提现">
                    <n-number-animation :from="0" :to="withdrawableAmount" :duration="1000" />
                    <template #suffix>元</template>
                  </n-statistic>
                </n-grid-item>
              </n-grid>

              <div class="chart-container">
                <h3>收益趋势</h3>
                <div class="earnings-chart" ref="earningsChartRef"></div>
            </div>
            
              <div class="section-header">
              <h3>收益明细</h3>
                <n-space>
                  <n-date-picker v-model:value="earningsDateRange" type="daterange" clearable />
                  <n-select v-model:value="earningsType" :options="earningsTypeOptions" style="width: 120px" />
                </n-space>
            </div>

              <div class="earnings-stats">
                <div class="stat-card">
                  <div class="stat-value">¥{{ totalEarnings }}</div>
                  <div class="stat-label">总收益</div>
          </div>
                <div class="stat-card">
                  <div class="stat-value">¥{{ monthlyEarnings }}</div>
                  <div class="stat-label">本月收益</div>
                </div>
                <div class="stat-card">
                  <div class="stat-value">¥{{ withdrawableAmount }}</div>
                  <div class="stat-label">可提现</div>
                </div>
              </div>

              <n-data-table :columns="earningsColumns" :data="filteredEarningsData" :loading="loading" :pagination="earningsPagination"
                :bordered="false" striped />

              <div class="withdraw-section">
                <h3>提现申请</h3>
                <n-card>
                  <n-form :model="withdrawForm" label-placement="left" label-width="100">
                    <n-form-item label="提现金额" path="amount">
                      <n-input-number v-model:value="withdrawForm.amount" :min="1" :max="withdrawableAmount" />
                    </n-form-item>
                    <n-form-item label="提现方式" path="method">
                      <n-select v-model:value="withdrawForm.method" :options="withdrawMethodOptions" />
                    </n-form-item>
                    <n-form-item label="账户信息" path="account">
                      <n-input v-model:value="withdrawForm.account" placeholder="请输入提现账户" />
                    </n-form-item>
                    <n-form-item>
                      <n-button type="primary" @click="submitWithdraw" :disabled="withdrawForm.amount <= 0">
                        申请提现
                      </n-button>
                    </n-form-item>
                  </n-form>
                </n-card>
            </div>
            </div>
          </div>
        </n-tab-pane>

        <!-- 粉丝管理标签页 -->
        <n-tab-pane name="fans" tab="粉丝管理">
          <div class="tab-content">
            <div class="fans-summary">
              <n-grid :cols="4" :x-gap="12">
                <n-grid-item>
                  <n-statistic label="总粉丝数">
                    <n-number-animation :from="0" :to="totalFans" :duration="1000" />
                  </n-statistic>
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="本月新增">
                    <n-number-animation :from="0" :to="newFansThisMonth" :duration="1000" />
                  </n-statistic>
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="互动率">
                    <template #default>{{ interactionRate }}%</template>
                  </n-statistic>
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="活跃粉丝">
                    <n-number-animation :from="0" :to="activeFans" :duration="1000" />
                  </n-statistic>
                </n-grid-item>
              </n-grid>

              <div class="chart-container">
                <h3>粉丝增长趋势</h3>
                <div class="fans-chart" ref="fansChartRef"></div>
              </div>

              <div class="section-header">
              <h3>粉丝列表</h3>
                <n-space>
                  <n-input v-model:value="fansSearch" placeholder="搜索粉丝" />
                  <n-select v-model:value="fansFilter" :options="fansFilterOptions" style="width: 120px" />
                </n-space>
              </div>

              <n-data-table :columns="fansColumns" :data="filteredFans" :loading="loading" :pagination="pagination"
                :bordered="false" striped />
            </div>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>

    <!-- 上传素材模态框 -->
    <n-modal v-model:show="showUploadModal" preset="card" title="上传素材" style="width: 600px">
      <n-form :model="uploadForm" label-placement="left" label-width="100">
        <n-form-item label="素材名称" path="name">
          <n-input v-model:value="uploadForm.name" placeholder="请输入素材名称" />
        </n-form-item>
        <n-form-item label="素材类型" path="type">
          <n-select v-model:value="uploadForm.type" :options="assetTypeOptions" />
        </n-form-item>
        <n-form-item label="素材分类" path="category">
          <n-select v-model:value="uploadForm.category" :options="categoryOptions" />
        </n-form-item>
        <n-form-item label="素材文件" path="file">
          <n-upload action="#" :default-upload="false" :max="1" @change="handleUploadChange">
            <n-button>选择文件</n-button>
          </n-upload>
        </n-form-item>
        <n-form-item label="缩略图" path="thumbnail">
          <n-upload action="#" :default-upload="false" :max="1" @change="handleThumbnailChange" accept="image/*">
            <n-button>选择缩略图</n-button>
          </n-upload>
        </n-form-item>
        <n-form-item label="描述" path="description">
          <n-input v-model:value="uploadForm.description" type="textarea" placeholder="请输入素材描述" />
        </n-form-item>
        <n-form-item label="标签" path="tags">
          <n-dynamic-tags v-model:value="uploadForm.tags" />
        </n-form-item>
        <n-form-item label="许可证" path="license">
          <n-select v-model:value="uploadForm.license" :options="licenseOptions" />
        </n-form-item>
        <n-form-item label="价格" path="price">
          <n-input-number v-model:value="uploadForm.price" :min="0" :precision="2"
            :disabled="uploadForm.license === 'free'" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showUploadModal = false">取消</n-button>
          <n-button type="primary" @click="submitUpload" :loading="uploading">上传</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NTabs,
  NTabPane,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NButton,
  NSpace,
  NDataTable,
  NDynamicTags,
  NTag,
  NDivider,
  NPagination,
  NStatistic,
  NIcon,
  NNumberAnimation,
  NDatePicker,
  NUpload,
  NModal,
  NInputGroup,
  NGrid,
  NGridItem,
  NButtonGroup
} from 'naive-ui'
import {
  RefreshOutline,
  SearchOutline,
  CloudUploadOutline,
  DownloadOutline,
  StarOutline,
  PersonOutline,
  CalendarOutline,
  TimeOutline,
  AddOutline
} from '@vicons/ionicons5'
import type { Project } from '../../types/project'
import type { UploadFileInfo } from 'naive-ui'
import dayjs from 'dayjs'

// 定义资产类型接口
interface Asset {
  id: string;
  name: string;
  type: string;
  categoryId: string;
  creatorId: string;
  thumbnail: string;
  description: string;
  tags: string[];
  createdAt: Date;
  updatedAt: Date;
  downloadCount: number;
  rating: number;
  price: number;
  isPremium: boolean;
  license: string;
  status: string;
}

// 定义收益记录类型接口
interface EarningRecord {
  id: string;
  date: Date;
  type: string;
  content: string;
  amount: number;
  status: string;
}

// 定义粉丝类型接口
interface Fan {
  id: string;
  username: string;
  followDate: Date;
  interactions: number;
  lastInteraction: Date | null;
}

// 定义上传表单文件类型
interface UploadForm {
  name: string;
  type: string;
  category: string;
  tags: string[];
  description: string;
  price: number;
  license: string;
  file: UploadFileInfo | null;
  thumbnail: UploadFileInfo | null;
}

// 路由和消息
const router = useRouter()
const message = useMessage()

// 加载状态
const loading = ref(false)

// 通用分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 40],
  onChange: (page: number) => {
    pagination.page = page
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize
    pagination.page = 1
  }
})

// ==================== 作品管理 ====================
// 作品搜索和筛选
const worksSearch = ref('')
const worksFilter = ref('')
const worksFilterOptions = [
  { label: '全部', value: '' },
  { label: '已发布', value: 'published' },
  { label: '草稿', value: 'draft' },
  { label: '审核中', value: 'pending' }
]

// 作品数据
const works = ref<Project[]>([])

// 作品表格列
const worksColumns = [
  {
    title: '作品名称',
    key: 'name'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    render(row: Project) {
      return formatDate(row.createdAt)
    }
  },
  {
    title: '最后修改',
    key: 'updatedAt',
    render(row: Project) {
      return formatDate(row.updatedAt)
    }
  },
  {
    title: '状态',
    key: 'status'
  },
  {
    title: '数据统计',
    key: 'stats'
  },
  {
    title: '操作',
    key: 'actions'
  }
]

// 过滤作品
const filteredWorks = computed(() => {
  let result = works.value

  // 搜索过滤
  if (worksSearch.value) {
    const searchLower = worksSearch.value.toLowerCase()
    result = result.filter(work =>
      work.name.toLowerCase().includes(searchLower) ||
      (work.description && work.description.toLowerCase().includes(searchLower))
    )
  }

  // 状态过滤
  if (worksFilter.value !== '') {
    result = result.filter(work => work.status === worksFilter.value)
  }

  return result
})

// 作品操作函数
function editProject(id: string) {
  router.push(`/workspace/editor?projectId=${id}`)
}

function viewProjectStats(id: string) {
  message.info(`查看作品数据: ${id}`)
}

function deleteProject(id: string) {
  message.warning(`删除作品: ${id}`)
}

// ==================== 素材管理 ====================
// 素材搜索和筛选
const assetsSearch = ref('')
const assetsFilter = ref('')
const assetsFilterOptions = [
  { label: '全部素材', value: 'all' },
  { label: '审核中', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已拒绝', value: 'rejected' }
]

// 素材分页
const assetsPage = ref(1)
const assetsTotalPages = ref(5)

// 素材数据
const assets = ref<Asset[]>([])
const assetsPagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// 素材上传模态框
const showUploadModal = ref(false)
const uploading = ref(false)
const uploadForm = reactive<UploadForm>({
  name: '',
  type: 'character',
  category: 'general',
  tags: [],
  description: '',
  price: 0,
  license: 'free',
  file: null,
  thumbnail: null
})

// 素材类型选项
const assetTypeOptions = [
  { label: '角色', value: 'character' },
  { label: '场景', value: 'scene' },
  { label: '音频', value: 'audio' },
  { label: '特效', value: 'effect' },
  { label: '动作', value: 'action' }
]

// 素材分类选项
const categoryOptions = [
  { label: '通用', value: 'general' },
  { label: '人物', value: 'human' },
  { label: '动物', value: 'animal' },
  { label: '场景', value: 'scene' },
  { label: '道具', value: 'prop' }
]

// 许可证选项
const licenseOptions = [
  { label: '免费', value: 'free' },
  { label: '商业使用', value: 'commercial' },
  { label: '仅限个人使用', value: 'personal' }
]

// 过滤素材
const filteredAssets = computed(() => {
  let result = assets.value

  // 搜索过滤
  if (assetsSearch.value) {
    const searchLower = assetsSearch.value.toLowerCase()
    result = result.filter((asset: any) =>
      asset.name.toLowerCase().includes(searchLower) ||
      (asset.description && asset.description.toLowerCase().includes(searchLower))
    )
  }

  // 状态过滤
  if (assetsFilter.value !== 'all') {
    result = result.filter((asset: any) => asset.status === assetsFilter.value)
  }

  return result
})

// 素材状态类型和文本
function getAssetStatusType(status: string): 'success' | 'warning' | 'info' | 'error' {
  const statusMap: Record<string, 'success' | 'warning' | 'info' | 'error'> = {
    approved: 'success',
    pending: 'warning',
    rejected: 'error'
  }
  return statusMap[status] || 'info'
}

function getAssetStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    approved: '已通过',
    pending: '审核中',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 素材操作函数
function editAsset(id: string) {
  message.info(`编辑素材: ${id}`)
}

function viewAssetStats(id: string) {
  message.info(`查看素材数据: ${id}`)
}

function deleteAsset(id: string) {
  message.warning(`删除素材: ${id}`)
}

// 上传处理函数
function handleUploadChange(options: { fileList: UploadFileInfo[] }) {
  uploadForm.file = options.fileList.length > 0 ? options.fileList[0] : null
}

function handleThumbnailChange(options: { fileList: UploadFileInfo[] }) {
  uploadForm.thumbnail = options.fileList.length > 0 ? options.fileList[0] : null
}

function submitUpload() {
  if (!uploadForm.name || !uploadForm.type || !uploadForm.category || !uploadForm.file) {
    message.error('请填写必填项')
    return
  }

  uploading.value = true

  // 模拟上传过程
  setTimeout(() => {
    uploading.value = false
    showUploadModal.value = false
    message.success('素材上传成功，等待审核')

    // 重置表单
    Object.assign(uploadForm, {
      name: '',
      type: '',
      category: '',
      file: null,
      thumbnail: null,
      description: '',
      tags: [],
      license: 'free',
      price: 0
    })

    // 刷新素材列表
    fetchAssets()
  }, 1500)
}

// ==================== 收益统计 ====================
// 收益数据
const totalEarnings = ref(3580.50)
const monthlyEarnings = ref(680.25)
const withdrawableAmount = ref(2450.75)

// 收益筛选
const earningsDateRange = ref(null)
const earningsType = ref('all')
const earningsTypeOptions = [
  { label: '全部收益', value: 'all' },
  { label: '素材销售', value: 'asset' },
  { label: '打赏收入', value: 'donation' },
  { label: '广告分成', value: 'ad' }
]

// 收益表格列
const earningsColumns = [
  {
    title: '时间',
    key: 'date',
    render(row: any) {
      return formatDate(row.date)
    }
  },
  {
    title: '类型',
    key: 'type',
    render(row: any) {
      const typeMap: Record<string, { text: string, type: 'success' | 'warning' | 'info' }> = {
        asset: { text: '素材销售', type: 'success' },
        donation: { text: '打赏收入', type: 'info' },
        ad: { text: '广告分成', type: 'warning' }
      }
      const type = typeMap[row.type] || { text: row.type, type: 'info' }
      return h(NTag, { type: type.type }, { default: () => type.text })
    }
  },
  {
    title: '内容',
    key: 'content'
  },
  {
    title: '金额',
    key: 'amount',
    render(row: any) {
      return h('span',
        { style: `color: ${row.amount > 0 ? 'var(--success-color)' : 'var(--error-color)'}` },
        `¥${row.amount.toFixed(2)}`
      )
    }
  },
  {
    title: '状态',
    key: 'status',
    render(row: any) {
      const statusMap: Record<string, { text: string, type: 'success' | 'warning' | 'info' | 'error' }> = {
        completed: { text: '已完成', type: 'success' },
        pending: { text: '处理中', type: 'warning' },
        failed: { text: '失败', type: 'error' }
      }
      const status = statusMap[row.status] || { text: row.status, type: 'info' }
      return h(NTag, { type: status.type }, { default: () => status.text })
    }
  }
]

// 收益数据
const earningsData = ref<EarningRecord[]>([])
const earningsFilter = reactive({
  dateRange: null,
  type: null
})
const earningsPagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// 提现表单
const withdrawForm = reactive({
  amount: 0,
  method: 'alipay',
  account: ''
})

// 提现方式选项
const withdrawMethodOptions = [
  { label: '支付宝', value: 'alipay' },
  { label: '微信', value: 'wechat' },
  { label: '银行卡', value: 'bank' }
]

// 提现申请
function submitWithdraw() {
  if (withdrawForm.amount <= 0) {
    message.error('请输入有效的提现金额')
    return
  }

  if (!withdrawForm.account) {
    message.error('请输入提现账户')
    return
  }

  message.loading('提交提现申请中...')

  // 模拟提现过程
  setTimeout(() => {
    message.success('提现申请已提交，请等待处理')
    withdrawableAmount.value -= withdrawForm.amount

    // 重置表单
    withdrawForm.amount = 0
    withdrawForm.account = ''

    // 刷新收益数据
    fetchEarningsData()
  }, 1000)
}

// 收益数据过滤
const filteredEarningsData = computed(() => {
  let result = [...earningsData.value];
  
  if (earningsFilter.dateRange && Array.isArray(earningsFilter.dateRange)) {
    // 根据日期范围过滤
    const startDate = earningsFilter.dateRange[0] ? new Date(earningsFilter.dateRange[0]) : null;
    const endDate = earningsFilter.dateRange[1] ? new Date(earningsFilter.dateRange[1]) : null;
    
    if (startDate && endDate) {
      result = result.filter(item => {
        const itemDate = new Date(item.date);
        return itemDate >= startDate && itemDate <= endDate;
      });
    }
  }
  
  if (earningsFilter.type) {
    // 根据收益类型过滤
    result = result.filter(item => item.type === earningsFilter.type);
  }
  
  return result;
})

// ==================== 粉丝管理 ====================
// 粉丝数据
const totalFans = ref(1280)
const newFansThisMonth = ref(78)
const interactionRate = ref(35.6)
const activeFans = ref(456)

// 粉丝搜索和筛选
const fansSearch = ref('')
const fansFilter = ref('')
const fansFilterOptions = [
  { label: '全部粉丝', value: 'all' },
  { label: '活跃粉丝', value: 'active' },
  { label: '新粉丝', value: 'new' }
]

// 粉丝表格列
const fansColumns = [
  {
    title: '用户名',
    key: 'username',
    render(row: any) {
      return h('div', { style: 'display: flex; align-items: center;' }, [
        h(NIcon, { size: 24, style: 'margin-right: 8px;' }, { default: () => h(PersonOutline) }),
        h('span', null, row.username)
      ])
    }
  },
  {
    title: '关注时间',
    key: 'followDate',
    render(row: any) {
      return formatDate(row.followDate)
    }
  },
  {
    title: '互动次数',
    key: 'interactions'
  },
  {
    title: '最近互动',
    key: 'lastInteraction',
    render(row: any) {
      return row.lastInteraction ? formatDate(row.lastInteraction) : '无互动'
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row: any) {
      return h(NSpace, null, {
        default: () => [
          h(
            NButton,
            {
              size: 'small',
              onClick: () => viewFanProfile(row.id)
            },
            { default: () => '查看主页' }
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => sendMessage(row.id)
            },
            { default: () => '发送消息' }
          )
        ]
      })
    }
  }
]

// 模拟粉丝数据
const fans = ref<Fan[]>([])
const fansPagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// 过滤粉丝
const filteredFans = computed(() => {
  let result = fans.value

  // 搜索过滤
  if (fansSearch.value) {
    const searchLower = fansSearch.value.toLowerCase()
    result = result.filter((fan: any) =>
      fan.username.toLowerCase().includes(searchLower)
    )
  }

  // 类型过滤
  if (fansFilter.value === 'active') {
    result = result.filter((fan: any) => fan.interactions > 5)
  } else if (fansFilter.value === 'new') {
    const oneMonthAgo = new Date()
    oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1)
    result = result.filter((fan: any) => new Date(fan.followDate) > oneMonthAgo)
  }

  return result
})

// 粉丝操作函数
function viewFanProfile(id: string) {
  router.push(`/user-profile/${id}`)
}

function sendMessage(id: string) {
  message.info(`发送消息给用户: ${id}`)
}

// ==================== 通用功能 ====================
// 日期格式化
function formatDate(date: Date | string): string {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 刷新数据
function refreshData() {
  loading.value = true

  Promise.all([
    fetchWorks(),
    fetchAssets(),
    fetchEarningsData(),
    fetchFans()
  ]).finally(() => {
    loading.value = false
    message.success('数据已刷新')
  })
}

// 获取作品数据
function fetchWorks() {
  return new Promise<void>(resolve => {
    setTimeout(() => {
      works.value = Array.from({ length: 10 }, (_, i) => ({
        id: `project-${i + 1}`,
        name: `作品 ${i + 1}`,
        description: `这是作品 ${i + 1} 的描述`,
        ownerId: 'current-user',
        createdAt: new Date(Date.now() - Math.random() * 10000000000),
        updatedAt: new Date(Date.now() - Math.random() * 1000000000),
        duration: 60000,
        frameRate: 30,
        resolution: {
          width: 1920,
          height: 1080,
          aspectRatio: '16:9'
        },
        thumbnail: `https://picsum.photos/id/${100 + i}/200/112`,
        status: ['published', 'draft', 'private'][Math.floor(Math.random() * 3)],
        visibility: 'public',
        characters: [],
        scenes: [],
        timeline: {
          id: `timeline-${i}`,
          projectId: `project-${i + 1}`,
          duration: 60000,
          tracks: [],
          currentTime: 0
        },
        version: 1,
        isTemplate: false,
        views: Math.floor(Math.random() * 1000),
        likes: Math.floor(Math.random() * 100),
        comments: Math.floor(Math.random() * 50)
      }))
      resolve()
    }, 500)
  })
}

// 获取素材数据
function fetchAssets() {
  return new Promise<void>(resolve => {
    setTimeout(() => {
      const newAssets: Asset[] = Array.from({ length: 12 }, (_, i) => ({
        id: `asset-${i + 1}`,
        name: `素材 ${i + 1}`,
        type: ['character', 'scene', 'audio', 'effect', 'action'][Math.floor(Math.random() * 5)],
        categoryId: ['general', 'human', 'animal', 'scene', 'prop'][Math.floor(Math.random() * 5)],
        creatorId: 'current-user-id',
        thumbnail: `https://picsum.photos/id/${i + 50}/200/200`,
        description: `这是素材 ${i + 1} 的描述`,
        tags: ['皮影', '动画', '2D'],
        createdAt: new Date(Date.now() - Math.random() * 10000000000),
        updatedAt: new Date(Date.now() - Math.random() * 1000000000),
        downloadCount: Math.floor(Math.random() * 500),
        rating: Math.floor(Math.random() * 5) + 1,
        price: Math.random() > 0.7 ? Math.floor(Math.random() * 100) + 10 : 0,
        isPremium: Math.random() > 0.7,
        license: ['free', 'commercial', 'personal'][Math.floor(Math.random() * 3)],
        status: ['active', 'pending', 'rejected'][Math.floor(Math.random() * 3)]
      }))
      assets.value = newAssets
      assetsPagination.itemCount = assets.value.length
      resolve()
    }, 500)
  })
}

// 获取收益数据
function fetchEarningsData() {
  return new Promise<void>(resolve => {
    setTimeout(() => {
      const newEarnings: EarningRecord[] = Array.from({ length: 20 }, (_, i) => {
        const type = ['asset', 'donation', 'ad'][Math.floor(Math.random() * 3)]
        let content = ''
        
        switch (type) {
          case 'asset':
            content = `素材《素材 ${Math.floor(Math.random() * 10) + 1}》销售`
            break
          case 'donation':
            content = `用户 user_${Math.floor(Math.random() * 1000)} 的打赏`
            break
          case 'ad':
            content = `广告分成 - ${Math.floor(Math.random() * 1000)}次展示`
            break
        }
        
        return {
          id: `earning-${i + 1}`,
          date: new Date(Date.now() - Math.random() * 10000000000),
          type,
          content,
          amount: Math.floor(Math.random() * 100) + 5,
          status: ['completed', 'pending', 'failed'][Math.floor(Math.random() * 3)]
        }
      })
      earningsData.value = newEarnings
      earningsPagination.itemCount = earningsData.value.length
      resolve()
    }, 500)
  })
}

// 获取粉丝数据
function fetchFans() {
  return new Promise<void>(resolve => {
    setTimeout(() => {
      const newFans: Fan[] = Array.from({ length: 20 }, (_, i) => {
        const interactions = Math.floor(Math.random() * 20)
        const hasInteraction = interactions > 0
        
        return {
          id: `fan-${i + 1}`,
          username: `user_${Math.floor(Math.random() * 1000)}`,
          followDate: new Date(Date.now() - Math.random() * 10000000000),
          interactions,
          lastInteraction: hasInteraction ? new Date(Date.now() - Math.random() * 1000000000) : null
        }
      })
      fans.value = newFans
      fansPagination.itemCount = fans.value.length
      resolve()
    }, 500)
  })
}

// 初始化数据
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.creator-center-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .creator-card {
    .card-header {
    display: flex;
      justify-content: space-between;
    align-items: center;

      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }

      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }

  .tab-content {
    padding: 16px 0;
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .asset-card {
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-4px);
    }

    .asset-thumbnail {
      width: 100%;
      height: 150px;
      object-fit: cover;
    }

    .asset-info {
      margin-top: 8px;

      .asset-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        span {
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }

      .asset-stats {
        display: flex;
        justify-content: space-between;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }
    }

    .asset-actions {
      display: flex;
      justify-content: center;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .earnings-summary {
    .chart-container {
      margin: 24px 0;

      h3 {
        margin-top: 0;
      margin-bottom: 16px;
        font-size: 18px;
      font-weight: 500;
    }
    
      .earnings-chart,
      .fans-chart {
        height: 300px;
        background-color: var(--card-color);
        border-radius: 4px;
        border: 1px solid var(--border-color);
      }
    }

    .withdraw-section {
      margin-top: 24px;

      h3 {
        margin-top: 0;
        margin-bottom: 16px;
        font-size: 18px;
        font-weight: 500;
      }
    }
  }

  .fans-summary {
    .fans-chart {
      margin-bottom: 24px;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .creator-center-container {
    padding: 12px;

    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }
  }
}
</style> 